package com.nami.framework.security.handler;

import com.nami.common.response.R;
import com.nami.common.response.ResponseCodeEnum;
import com.nami.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Security 无权限处理 Handler
 *
 * @author chengh
 */
@Slf4j
@Component
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        log.info("用户无权限处理器~");
        if (ServletUtils.isAjax(request)) {
            R<Void> r = R.failed(ResponseCodeEnum.FAILED_403.getCode(), ResponseCodeEnum.FAILED_403.getMessage());
            ServletUtils.writeJson(r);
        } else {
            response.sendRedirect("/error/403");
        }
    }
}
